import java.time.LocalTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Author Stringzhua
 * @Date 2024/10/30 16:14
 * description:
 * ScheduledExecutorService是ThreadPoolExecutor的子类
 * 继承自ThreadPoolExecutor,并且添加了三个方法
 * <p>
 * NANOSECONDS 纳秒
 * new DelayedWorkQueue() 延迟工作队列,存放的是即将要被执行的任务
 * <p>
 * public ScheduledThreadPoolExecutor(int corePoolSize) {
 * super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
 * new DelayedWorkQueue());
 * }
 */
public class ThreadPool06 {
    public static void main(String[] args) {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
        System.out.println(LocalTime.now() + "start!");

        //延迟一秒钟后执行任务
        executorService.schedule(new Task(),3, TimeUnit.SECONDS);
        executorService.shutdown();

        //延迟2秒钟后第一次执行任务,然后每隔5秒钟执行一次任务
        //方式1:FixedRate是指任务总是以固定时间间隔触发，不管任务执行多长时间;
//        executorService.scheduleAtFixedRate(new Task(), 2, 5, TimeUnit.SECONDS);

        //方式2:FixedDelay是指，上一次任务执行完毕后，等待固定的时间间隔，再执行下一次任务;
//        executorService.scheduleWithFixedDelay(new Task(), 2, 5, TimeUnit.SECONDS);


    }

}

class Task implements Runnable {
    @Override
    public void run() {
        try {
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(LocalTime.now() + "时" + Thread.currentThread().getName() + "执行任务");
    }
}
